<template>
  <div
    class="diy-goods component-diy"
    :style="{
      marginTop: componentData.data.marginTop + 'px',
      marginBottom: componentData.data.marginBottom + 'px',
      padding: `0 ${componentData.data.marginLeftRight}px`,
    }"
  >
    <div
      class="goods-list"
      :class="layout ? layout : componentData.data.layout"
      v-if="goodsList && goodsList.length > 0"
      :style="{
        backgroundColor: componentData.data.bgColor,
        padding: `${componentData.data.paddingTopBottom}px ${componentData.data.paddingLeftRight}px`,
        borderRadius: cardStyle == 2 ? '0' : '8px',
      }"
    >
      <template v-for="(item, index) in goodsList">
        <div
          @click.stop="toGoodsDetail(item.goods_id)"
          class="goods"
          :style="{
            padding: componentData.data.goodsMargin + 'px',
            borderRadius: componentData.data.goodsRadius + 'px',
          }"
          :key="index"
        >
          <div
            class="animationIcon"
          >
          <block v-for="(animation) in animations" :key="animation.id">
            <div
              :class="{ baltRight: index % 2 === 0, balt: index % 2 !== 0 }"
               v-if="animation.active && animationIndex === index " 
            >
              <div
                :class="{ innerRight: index % 2 === 0, inner: index % 2 !== 0 }"
              ></div>
            </div>
          </block>
           
          </div>

          <div
            :class="['link', 'link-card-type-' + componentData.data.cardType]"
            :style="{
              borderRadius: componentData.data.goodsRadius + 'px',
            }"
          >
            <div
              class="img"
              :id="'img-ctx-' + index"
              :style="{
                backgroundImage: `url(${item.goods_img})`,
                height:
                  imageHeight === ''
                    ? 'auto'
                    : imageHeight *
                        (componentData.data.layout === 'one-big-two-small' &&
                        index % 3 !== 0
                          ? 0.5
                          : 1) +
                      'px',
              }"
            >
              <div v-if="componentData.data.cornerMark" class="corner-mark">
                <template
                  v-if="
                    componentData.data.cornerMarkType === 1 &&
                    componentData.data.cornerMarkText
                  "
                >
                  <div
                    class="corner-mark-text"
                    :style="{
                      color: componentData.data.cornerMarkColor,
                      backgroundColor:
                        componentData.data.cornerMarkBackgroundColor,
                    }"
                  >
                    {{ componentData.data.cornerMarkText }}
                  </div>
                </template>
                <template v-if="componentData.data.cornerMarkType === 2">
                  <img
                    :src="componentData.data.cornerMarkImage"
                    style="width: 30px; height: 30px"
                  />
                </template>
              </div>
            </div>

            <div class="goods-info-wrap">
              <div class="goods-info-box" @click.stop="()=>{}">
                <div
                  v-if="componentData.data.title"
                  :class="[
                    'title',
                    componentData.data.titleLine == 2 ? 'line2' : '',
                  ]"
                  :style="{
                    color: componentData.data.titleColor,
                    fontSize: componentData.data.titleFontSize + 'px',
                    fontWeight: componentData.data.titleFontWeight,
                    lineHeight: componentData.data.titleFontSize + 6 + 'px',
                  }"
                >
                  {{ item.goods_name }}
                </div>
                <div
                  v-if="componentData.data.subTitle"
                  :class="[
                    'title',
                    componentData.data.subTitleLine == 2 ? 'line2' : '',
                  ]"
                  :style="{
                    color: componentData.data.subTitleColor,
                    fontSize: componentData.data.subTitleFontSize + 'px',
                    fontWeight: componentData.data.subTitleFontWeight,
                    lineHeight: componentData.data.subTitleFontSize + 6 + 'px',
                  }"
                >
                  <span
                    v-if="!!layout"
                    style="text-decoration: line-through; font-size: 12px"
                    >原价{{ item.online_price }}</span
                  >
                  <span v-else>{{
                    item.subheading ? item.subheading : ""
                  }}</span>
                </div>

                <div class="price-cart">
                  <div>
                    <div
                      v-if="
                        (componentData.data.price && showOnlinePrice(item)) ||
                        !!layout
                      "
                      class="price"
                      :style="{
                        color: componentData.data.priceColor || '#FF7342',
                        fontSize:
                          (componentData.data.priceFontSize || 12) + 'px',
                        fontWeight: componentData.data.priceFontWeight,
                      }"
                    >
                      <span v-if="!!layout" style="font-size: 14px">抢购</span>
                      <span v-if="!layout" style="font-weight: bold"
                        >￥{{ item.online_price }}</span
                      >
                      <span v-else style="font-weight: bold"
                        >￥{{ oldData.min_price }}</span
                      >
                    </div>

                    <div
                      v-if="
                        item.shop_mem_price && showVipPrice(item) && !layout
                      "
                      class="price"
                      :style="{
                        color: componentData.data.vipPriceColor || '#FF7342',
                        fontSize:
                          (componentData.data.priceFontSize || 12) + 'px',
                        fontWeight: componentData.data.priceFontWeight,
                      }"
                    >
                      <div
                        style="display: flex; height: 20px; line-height: 20px"
                        v-if="vipPriceType"
                      >
                        <i
                          :style="{
                            color: componentData.data.vipIconPriceColor,
                          }"
                          v-if="vipPriceType.float == 'left'"
                          :class="[
                            `iconfont`,
                            `icon_left`,
                            `icon-member-price${vipPriceType.key}`,
                          ]"
                        ></i>
                        <span style="font-weight: bold"
                          >￥{{ item.shop_mem_price }}</span
                        >
                        <i
                          :style="{
                            color: componentData.data.vipIconPriceColor,
                          }"
                          v-if="vipPriceType.float == 'right'"
                          :class="[
                            `iconfont`,
                            `icon_right`,
                            `icon-member-price${vipPriceType.key}`,
                          ]"
                        ></i>
                      </div>
                    </div>
                    <div
                      v-if="item.plus_price && showPlusPrice(item) && !layout"
                      class="plus_price"
                      :style="{
                        color: componentData.data.PlusPriceColor || '#FF7342',
                        fontSize:
                          (componentData.data.priceFontSize || 12) + 'px',
                        fontWeight: componentData.data.priceFontWeight,
                      }"
                    >
                      <div
                        v-if="plusPriceType"
                        style="display: flex; height: 20px; line-height: 20px"
                        class="price"
                      >
                        <i
                          :style="{
                            color: componentData.data.PlusIconPriceColor,
                          }"
                          v-if="plusPriceType.float == 'left'"
                          :class="[
                            `iconfont`,
                            `icon_left`,
                            `icon-plus${plusPriceType.key}`,
                          ]"
                        ></i>
                        <span style="font-weight: bold"
                          >￥{{ item.plus_price }}</span
                        >
                        <i
                          :style="{
                            color: componentData.data.PlusIconPriceColor,
                          }"
                          v-if="plusPriceType.float == 'right'"
                          :class="[
                            `iconfont`,
                            `icon_right`,
                            `icon-plus${plusPriceType.key}`,
                          ]"
                        ></i> 
                      </div>
                    </div>
                  </div>

                  <div
                    v-if="
                      componentData.data.buyBtn &&
                      componentData.data.buyBtnType &&
                      buyBtn
                    "
                    :class="[carouselClass]"
                    style="position: absolute; right: 0px; bottom: 0px"
                  >
                        
                    <!-- <view
                          class="choose-sku-change-iccc border"
                        >
                          <text
                          class="minusjian-icon"
                           v-if="indexes.includes(index) "
                            @click.stop="reduceShopping(item, index)"
                          >-</text>
                          <view   v-if="indexes.includes(index) " style="width: 30rpx;display: flex;align-items: center;justify-content: center;" >
                            <view  style="font-size: 20rpx;">
                              {{ item.num }}
                            </view>
                          </view>
                          <text 
                          class="minusjia-icon"
                          @click.stop="addShopping(item, index)"
                          ></text>
                        </view> -->

                          <!-- :class="{'hidden':!item.num === 0 ,'visible-in':item.num > 0 ,'rotate':!item.num === 0 ,'icontext':!item.num > 0  }" -->

                    <template v-if="buyBtn.icon">
                      <div @click.stop="()=>{}" style="display: flex; justify-content: flex-end; align-items: flex-end; width: 326rpx; height: auto;">
                        <view class="container">
                          <view class="button-container" style="display: flex;">
                            <button
                              :disabled="item.num === 0 || item.num < 0"
                              @click="reduceShopping(item, index)"
                              class="roundBtn icontext" 
                              :class="buttonClass(item) ? 'hidden' : 'visible-in'"
                              style="flex: 1;"
                            > 
                              <text class="icontext" :class="{'rotate': item.num === 0}">-</text>
                            </button>

                            <view v-if="item.num > 0" style="width: 30rpx; display: flex; align-items: center; justify-content: center;">
                              <view style="font-size: 20rpx;">{{ item.num }}</view>
                            </view>

                            <button 
                              class="roundBtn"
                              @click="addShopping(item, index)"
                              style="flex: 1;"
                            >
                              <text class="icontext" :class="{'rotate': item.num > 0}">+</text>
                            </button>
                          </view>
                        </view>
                      </div>
                    </template>

                    <template v-else>
                      <div
                        :class="[
                          'el-button',
                          `el-button--${buyBtn.type}`,
                          buyBtn.type == 'plain'
                            ? 'el-button--primary is-plain'
                            : '',
                          'el-button--mini',
                        ]"
                        :style="
                          `border-radius:${buyBtn.round}px;` + buyBtnStyle
                        "
                      >
                        {{
                          componentData.data.buyBtnText
                            ? componentData.data.buyBtnText
                            : "立即购买"
                        }}
                      </div>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>
<script module="until" lang="wxs" src="../until.wxs"></script>
<script>
var app = getApp().globalData;
import diyNavigator from "../diy-navigator/diy-navigator";

import {
  buyBtnConfigData,
  getThemeCluster,
  vipPriceTypeData,
  plusPriceTypeData,
} from "@/pages/store/components/diy-goods/buy-btn.config.js";
export default {
  computed: {
    iconsType() {
      return false;
    },
  },
  components: {
    diyNavigator,
  },
  data() {
    return {
      btnClass: true,
      animations: [],
      canClick: true,
      animationIndex: null,
      indexes: [],
      dataList: [],
      goods: [],
      imagesStyle: "",
      imageHeight: 0,
      buyBtnConfigData,
      vipPriceTypeData,
      plusPriceTypeData,
      buyBtn: null,
      buyBtnStyle: "",
      vipPriceType: null,
      goodsList: [],
      vipPriceType: {
        key: 0,
        type: "none",
        float: "left",
        icon: "",
      },
      plusPriceType: {
        key: 1,
        float: "left",
      },
    };
  },
  /**
   * 组件的属性列表
   */
  props: {
    merchant: {
      type: Number,
      default: 0,
    },
    disable: {
      type: Number,
    },
    oldData: {
      type: Object,
    },
    componentData: {
      type: Object,
    },
    layout: {
      type: String,
    },
    cardStyle: {
      type: String,
    },
    noBegin: {
      // 0 进行中 1 未开始 2 已结束
      type: Number,
    },
    type: {
      type: String,
    },
  },
  watch: {
    "componentData.data.goodsList": {
      async handler() {
        let url;
        if (this.merchant == 1) {
          url = "DiyStore/Api/getGoods";
        } else {
          url = "SmallProgramApi/Diy/getRecommendGoods";
        }

        if (!this.componentData.data.goodsList.join(",")) {
          // 虚拟商品 不做数据加载
          return;
        }

        const res = await this.$request(url, {
          ids: this.componentData.data.goodsList.join(","),
        });

        this.$nextTick(() => {
          this.getDataList();
        });

        if (res.status == 1) {
          const data = res.data;

          this.goodsList = this.componentData.data.goodsList
            .map((id_res) => {
              return data.find((res) => {
                if (id_res == res.goods_id) {
                  return true;
                } else {
                  return false;
                }
              });
            })
            .filter((res) => {
              if (res) {
                return true;
              } else {
                return false;
              }
            });
          this.getHeight();
        }
      },
      immediate: true,
    },

    componentData: {
      handler: function () {
        const buyBtn = this.buyBtnConfigData.find((item) => {
          return item.key === this.componentData.data.buyBtnType;
        });
        if (buyBtn) {
          this.setData({
            buyBtn,
          });
        }
        if (buyBtn) {
          this.execBuyBtnStyle(buyBtn);
        }
        const vipPriceType = this.vipPriceTypeData.find((item) => {
          return item.key === this.componentData.data.vip_price_type;
        });
        if (vipPriceType) {
          this.setData({
            vipPriceType,
          });
        }
        const plusPriceType = this.plusPriceTypeData.find((item) => {
          return item.key === this.componentData.data.plus_price_type;
        });
        // console.log(plusPriceType);
        if (plusPriceType) {
          this.setData({
            plusPriceType,
          });
        }
      },

      immediate: true,
      deep: true,
    },
  },

  beforeMount() {},
  mounted() {
  
    // console.log("--检查商品数据--",this.componentData);
    const buyBtn = this.buyBtnConfigData.find((item) => {
      return item.key === this.componentData.data.buyBtnType;
    });
    buyBtn &&
      this.setData({
        buyBtn,
      });
    if (buyBtn) {
      this.execBuyBtnStyle(buyBtn);
    }
  },

  methods: {
    async getDataList() {
      this.$forceUpdate(); // 强制更新视图

      const {
        status,
        data: { list, count },
        message,
      } = await this.$request(
        "SmallProgramApi/MerchantShopping/getShoppingCartList"
      );

        // 购物车的数据和商品数据合并
        list.forEach((item) => {
          let existingItemIndex = this.goodsList.findIndex(
            (i) => i.goods_id === item.goods_id
          );
          if (existingItemIndex !== -1 && item.hasOwnProperty("num")) {
            this.$set(this.goodsList, existingItemIndex, {
              ...this.goodsList[existingItemIndex],
              ...item,
            }); // 使用 $set 方法更新数组元素
          }
        });

        //购物车的数据
        let updateCarList = this.$store.merShoppingGoodsList;
        this.goodsList.forEach((item) => {
          let matchedItem = updateCarList.find(
            (el) => el.goods_id === item.goods_id
          );
          if (matchedItem) {
            item.num = matchedItem.num;
          } else {
            this.indexes  = []
            item.num = 0;
          }
        });

        this.goodsList.forEach((item, index) => {
          if (item.num > 0) {
            this.indexes.push(index);
          }
        });
        this.indexes = [...new Set(this.indexes)];
      this.$forceUpdate();
    },

    buttonClass(item) {
        if (item.num === 0) {
            return true;
        } 
        if (item.count > 0) {

        return false
        }
    },
    // 加
    async addShopping(goods, index) {
      this.animationIndex = index;
      this.btnClass = true
      let item = {
        ...this.goodsList[index],
      };
      this.$set(this.goodsList, index, item);
      item.num++;
      console.log(item.num)
      if (this.animationIndex === index) {
        const animation = {
          id: Date.now(),
          active: true
        };
        this.animations.push(animation);
          setTimeout(() => {
            animation.active = false;
            setTimeout(() => {
            this.animations = this.animations.filter((anim) => anim.id !== animation.id);
            }, 1000);
          }, 1000);
      }
      const status = await this.$mutations.setShoppingCar({
        id: item.id,
        goods_id: item.goods_id,
        sku_id: item.sku_id,
        num: item.num,
      });
      if (status) {
        this.getDataList();
      }
    },
    // 减
    async reduceShopping(goods, index) {
      this.animationIndex = index;
        let item = {
          ...this.goodsList[index],
        };
        this.$set(this.goodsList, index, item);
        item.num--;
        if(item.num  === 0){
          this.btnClass = false
          let indexToDelete = this.indexes.indexOf(index);
            if (indexToDelete !== -1) {
              this.indexes.splice(indexToDelete, 1);
            }
        }
        const status = await this.$mutations.setShoppingCar({
          id: item.id,
          goods_id: item.goods_id,
          sku_id: item.sku_id,
          num: item.num,
        });
        if (status) {
          this.getDataList();
        }
            
    },  

    //第一次加入购物车
  async  addToCar(goods, index) {
      this.indexes.push(index);

      goods.num = 1
      if (!!this.layout) {
        if (this.noBegin != 0) {
          this.noBeginMsg();
          return false;
        }
        uni.navigateTo({
          url: this.oldData.path,
        });
        return;
      }
      if (goods.attribute_state == 1) {
        this.$emit("toAddToCar", {
          goods_id: goods.goods_id,
          num: 1,
        });
      } else if (goods.attribute_state == 2) {
        this.$emit("getSku", goods);
      }
    },

    toGoodsDetail(goodsId) {
      if (!!this.layout) {
        if (this.noBegin != 0) {
          this.noBeginMsg();
          return false;
        }
        uni.navigateTo({
          url: this.oldData.path,
        });
        return;
      }
      if (this.merchant == 1) {
        uni.navigateTo({
          url: "/pages/mer/goods/details/details?id=" + goodsId,
        });
      } else {
        uni.navigateTo({
          url:
            "/pages/product/details/details?id=" +
            goodsId +
            "&store_id=" +
            this.$root.store_id,
        });
      }
    },
    noBeginMsg() {
      // 0 进行中 1 未开始 2 已结束
      const { noBegin } = this;
      let title;

      if (!!noBegin) {
        if (noBegin == 2) {
          title = "活动已经结束";
        } else {
          title = "活动还未开始，待会儿在来试试吧";
        }
      }

      uni.showToast({
        title,
        icon: "none",
      });
    },

    noPathMsg(e) {
      this.$emit("toOrderFoot", {
        id: e.spu.product_id,
      });
    },

    callback(e) {
      const myEventDetail = {
        ...e.detail,
      }; // console.log('diy-img-callback',e,myEventDetail);

      this.$emit("callback", {
        detail: myEventDetail,
      });
    },

    execBuyBtnStyle(buyBtn) {
      if (buyBtn.icon) {
        return;
      } // console.log('execBuyBtnStyle',buyBtn,this.data.componentData.data);

      const { buyBtnColor } = this.componentData.data;
      const arr = getThemeCluster(buyBtnColor);
      const obj = {};

      if (buyBtn.type === "plain") {
        obj["border-color"] = `${arr[6]}!important`;
        obj["background-color"] = `${arr[10]}!important`;
        obj["color"] = `${buyBtnColor}!important`;
      } else if (buyBtn.type === "primary") {
        obj["border-color"] = `${buyBtnColor}!important`;
        obj["background-color"] = `${buyBtnColor}!important`;
        obj["color"] = `#fff !important`;
      } else if (buyBtn.type === "") {
      }

      const buyBtnStyle = Object.keys(obj)
        .map((key) => {
          return key + ":" + obj[key];
        })
        .join(";");
      this.setData({
        buyBtnStyle,
      });
    },
    // 展示plus会员价条件
    showPlusPrice(item) {
      return app.showPlusPrice(item);
    },
    // 展示会员价条件
    showVipPrice(item) {
      return app.showVipPrice(item);
    },

    // 展示普通价格
    showOnlinePrice(item) {
      return app.showOnlinePrice(item);
    },
    getHeight() {
      if (!this.goodsList.length) {
        return false;
      }
      this.getRect("#img-ctx-0")
        .then((res) => {
          // console.log(res);
          if (res === null) {
            return Promise.reject();
          }

          try {
            const arr = this.componentData.data.imgRatio.split(":");
            const imageHeight = (res.width * arr[1]) / arr[0];
            this.setData({
              imageHeight,
            });
          } catch (e) {}
        })
        .catch(() => {
          if (!this.getHeightNum) {
            this.getHeightNum = 1;
          } else {
            this.getHeightNum++;
          }

          if (this.getHeightNum > 10) {
            return false;
          }

          this.getHeight();
        });
    },

    getRect(selector) {
      return new Promise((resolve) => {
        uni
          .createSelectorQuery()
          .in(this)
          .select(selector)
          .boundingClientRect((rect) => {
            resolve(rect);
          })
          .exec();
      });
    },
  },
};
</script>
<style lang="less">
@import "./diy-goods.css";
</style>
<style lang="less">
@import "../../../../static/css/common-goods.css";
</style>


<style lang="less" scoped>
.animationIcon {
    position: relative;
    top: 458rpx;
    left: 245rpx;
  }
  
  .balt,
  .baltRight {
    position: absolute;
    width: 25rpx;
    height: 25rpx;
    border-radius: 50%;
    z-index: 99999;
  }
  
  .inner,
  .innerRight {
    background: red;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    z-index: 99999;
  }
  
  .balt {
    animation: moveX 1s 1;
  }
  
  .inner {
    animation: moveY 1s cubic-bezier(1, -1, 1, 10) 1;
  }
  
  .baltRight {
    animation: moveXR 1s 1;
  }
  
  .innerRight {
    animation: moveYR 1s cubic-bezier(1, -1, 1, 10) 1;
  }
  
  @keyframes moveX {
    50% {
      transform: translateX(-100px);
    }
  
    100% {
      transform: translateX(-100px);
    }
  }
  
  @keyframes moveY {
    50% {
      transform: translateY(1000px);
    }
    100% {
      transform: translateY(1000px);
    }
  }
  
  @keyframes moveXR {
    50% {
      transform: translateX(180px);
    }
  
    100% {
      transform: translateX(180px);
    }
  }
  
  @keyframes moveYR {
    50% {
      transform: translateY(1000px);
    }
    100% {
      transform: translateY(1000px);
    }
  }
</style>
